package cn.daliyTest.com.thread.processCommunication;

import java.util.ArrayList;
import java.util.List;

/**
 * wait和notify必须配合synchronized使用，wait释放锁
 *
 * @author ：ljf
 * @date ：Created in 2021/6/24 11:05
 */
public class TestSyncByNotifyAndWait {

    public static void main(String[] args) {
        Object lock = new Object();
        List<String> list = new ArrayList<>();

        Thread threadA = new Thread(() ->{
           synchronized (lock){
               for (int i = 0; i < 10 ; i++) {
                   list.add("abc");
                   System.out.println("A向list加数据，size ："+list.size());
                   try {
                       Thread.sleep(5000);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
                   if(list.size() == 5){
                       lock.notify();
                   }
               }
           }
        });

        Thread threadB = new Thread(() ->{
            while (true){
                synchronized (lock){
                    if(list.size() != 5){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("B 开始了");
                    break;
                }

            }
        });

        threadB.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        threadA.start();


    }
}
